package com.baseframe.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baseframe.auth.entity.UserBean;
import com.baseframe.auth.utils.AuthUtil;
import com.baseframe.mybatis.utils.BaseMetaObjectUtil;
import com.baseframe.tool.result.R;
import com.baseframe.user.entity.SnsUserRelation;
import com.baseframe.user.entity.request.SnsUserRelationRequest;
import com.baseframe.user.entity.vo.SnsUserRelationVO;
import com.baseframe.user.service.SnsUserRelationService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/front/user/relation")
@AllArgsConstructor
public class FrontSnsUserRelationController {

    private SnsUserRelationService snsUserRelationService;


    /**
     * 获取与指定用户的关系
     * @param request 请求参数
     * @return 响应
     */
    @GetMapping("/get")
    public R<Object> getRelation( SnsUserRelationRequest request){

        if(request.getFollowUserId() == null){
            return R.fail("缺少必要请求参数~");
        }

        UserBean userBean = AuthUtil.getUserBean();
        SnsUserRelationVO snsUserRelationVO = new SnsUserRelationVO();

        if(userBean == null){
            snsUserRelationVO.setFollow(false);

            return R.data(snsUserRelationVO);
        }



        return R.data(snsUserRelationService.getRelation(request));
    }


    /**
     * 关注或取消关注
     * @param request 请求参数
     * @return 响应
     */
    @PostMapping("/follow-or-unfollow")
    public R<Object> concernUser(@RequestBody SnsUserRelationRequest request){
        if(request.getFollowUserId() == null){
            return R.fail("缺少必要请求参数~");
        }

        if(Objects.equals(request.getFollowUserId(), AuthUtil.getUserId())){
            return R.fail("你不能关注自己~");
        }

        SnsUserRelation snsUserRelation = snsUserRelationService.getOne(new LambdaQueryWrapper<SnsUserRelation>().eq(SnsUserRelation::getUserId, AuthUtil.getUserId()).eq(SnsUserRelation::getFollowUserId, request.getFollowUserId()));

        //已关注，就取消关注
        if (snsUserRelation!=null){
           return snsUserRelationService.removeById(snsUserRelation.getId())?R.success():R.fail();
        }

        snsUserRelation = new SnsUserRelation();
        BeanUtils.copyProperties(request,snsUserRelation, BaseMetaObjectUtil.getInsertFillPropertiesName(snsUserRelation.getClass()));

        snsUserRelation.setUserId(AuthUtil.getUserId());

        snsUserRelation.setFollowTime(new Date());

        return snsUserRelationService.save(snsUserRelation)?R.success():R.fail();
    }


    /**
     * 获取好友列表
     * @return
     */
    @GetMapping("/buddy/list")
    public R<Object> getBuddyList(){

        return R.data(snsUserRelationService.getBuddyList());
    }




}
